package com.springboot.config;

import com.springboot.common.MyFailureHandler;
import com.springboot.common.MySuccessHandler;
import com.springboot.filter.VerificationCoderFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    @Autowired
    private MySuccessHandler mySuccessHandler;

    @Autowired
    private MyFailureHandler myFailureHandler;

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.rememberMe().and()
                .authorizeRequests()
                .antMatchers("/login", "/myLogin.html", "/myajax", "/js/**", "/images/**","/fonts/**","/css/**","/captcha/**","/mylogin","/myAjax.html").permitAll()
                .antMatchers("/access/user/**").hasAnyRole("USER", "ADMIN")
                .antMatchers("/access/read/**").hasAnyRole("READ", "ADMIN")
                .antMatchers("/access/admin/**").hasAnyRole("ADMIN")
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .successHandler(mySuccessHandler)
                .failureHandler(myFailureHandler)
                .loginPage("/mylogin")
                .loginProcessingUrl("/login")
                .and()
                .csrf().disable();


        //在框架的过滤器链条中，添加一个自定义过滤器
        http.addFilterBefore(new VerificationCoderFilter(), UsernamePasswordAuthenticationFilter.class);
    }
}
